package com.cdinternationalcompany.syhapp.push

import android.content.Context
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import com.cdinternationalcompany.syhapp.utils.ChannelManager
import com.heytap.msp.push.HeytapPushManager
import com.huawei.hms.aaid.HmsInstanceId
import com.huawei.hms.common.ApiException
import com.huawei.hms.push.HmsMessaging
import com.vivo.push.PushClient
import com.vivo.push.listener.IPushQueryActionListener
import com.xiaomi.mipush.sdk.MiPushClient


interface Observer {
    fun notify(platform: String, token: String)
}

class TokenObserver {
    companion object {
        private val TAG = "${Constants.tag}.${TokenObserver::class.java.simpleName}"
        val instance by lazy(LazyThreadSafetyMode.NONE) {
            TokenObserver()
        }
    }

    public val mObservers = mutableListOf<Observer>()

    fun register(observer: Observer) {
        mObservers.add(observer)
    }

    fun unRegister(observer: Observer) {
        mObservers.remove(observer)
    }

    fun publish(platform: String, token: String) {
        mObservers.forEach {
            it.notify(platform, token)
        }
        val para = mapOf<String,String>(Pair("token",token),Pair("platform",platform))
        ChannelManager.instance.callFlutter("PushApi/registerId", para)
    }


    fun collectionToken(context: Context) {
        // huawei token collector
        if (ManufacturerHelper.isHuaWei()) {
            Thread {
                run {
                    try {
                        val id = HmsInstanceId.getInstance(context).getToken("113492203", "HCM")
                        Log.d(TAG, "Hms token -> $id")

                        if (!TextUtils.isEmpty(id)) {
                            android.os.Handler(Looper.getMainLooper()).post{
                                publish("1", id)
                            }

                            HmsMessaging.getInstance(context).turnOnPush().addOnCompleteListener { task ->
                                if (task.isSuccessful) {
                                    Log.i(TAG, "turnOffPush successfully.")
                                } else {
                                    Log.i(TAG, "turnOffPush failed.")
                                }
                            }
                        }
                    } catch (e: ApiException) {
                        Log.e(TAG, "get token failed, $e")
                    }
                }
            }.start()
        } else if (ManufacturerHelper.isXiaoMi()) {
            val id = MiPushClient.getRegId(context)
            Log.d(TAG, "Xiaomi Register id -> $id")
            if (!TextUtils.isEmpty(id)) {
                publish("2", id)
            }
        } else if (ManufacturerHelper.isOPPO()) {
            // TOOD Oppo
            val id = HeytapPushManager.getRegisterID()
            Log.d(TAG, "Oppo Register id -> $id")
            if (!TextUtils.isEmpty(id)) {
                publish("4", id)
            }
        } else if (ManufacturerHelper.isViVo()) {
           PushClient.getInstance(context).getRegId(
               object : IPushQueryActionListener {
                   override fun onSuccess(regid: String?) {
                       //获取成功，回调参数即是当前应用的regid；
                       Log.d(TAG, "Vivo Register id -> $regid")
                       if (!TextUtils.isEmpty(regid)) {
                           if (regid != null) {
                               publish("3", regid)
                           }
                       }
                   }

                   override fun onFail(errerCode: Int?) {
                       //获取失败，可以结合错误码参考查询失败原因；
                   }
               },
           );

        }

//        TokenObserver.instance.collectionToken(context)
        // JPush
//        val registerId = JPushInterface.getRegistrationID(context)
//        if (!TextUtils.isEmpty(registerId)) {
//            publish("1", registerId)
//        }
//        Log.d(TAG, "JPush Register id -> $registerId")
    }

}